package com.hulk.dryad.manage.framework.datasource;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.hulk.dryad.common.util.SpringContextHolder;
import com.hulk.dryad.manage.framework.tenant.TenantHierarchyUtil;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hulk
 * @version 1.0
 * @date 2020/12/29 13:39
 */
public class JdbcTemplateDsFactory {

	private static final Map<String, JdbcTemplate> JDBC_MAP = new ConcurrentHashMap<>();


	public static JdbcTemplate instance() {

		String tenantId = TenantHierarchyUtil.getTenantId();
		if (StrUtil.isBlank(tenantId)) {
			return null;
		}
		JdbcTemplate jdbcTemplate = JDBC_MAP.get(tenantId);
		if (jdbcTemplate != null) {
			return jdbcTemplate;
		} else {
			DataSource dataSource = SpringContextHolder.getBean(DataSource.class);
			DynamicRoutingDataSource drds = (DynamicRoutingDataSource) dataSource;
			DataSource ds = drds.getDataSource(tenantId);
			JdbcTemplate jdbc = new JdbcTemplate(ds, true);
			JDBC_MAP.putIfAbsent(tenantId, jdbc);
			return jdbc;
		}
	}
}
